package itsm.isperp.framework.web.servlet;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.domain.UploadInfo;
import itsm.isperp.framework.service.UploadFileService;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2015-3-13
 * @since 1.0
 * 
 */
public class ImgSrcServlet extends HttpServlet implements InitializingBean {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	protected UploadFileService<UploadInfo> uploadFileService;

	/**
	 * 初始化
	 */
	@Override
	public void init() throws ServletException {

		if (this.uploadFileService == null) {
			this.uploadFileService = ContextHolder
					.getSpringBean("appUploadFileService");// 此处可设置为可配置

		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("image/*;charset=UTF-8");

		String path = req.getParameter("path");

		if (StringUtils.isEmpty(path)) {
			return;
		}

		String filePath = ContextHolder.getApplicationPath() + path;
		File f = new File(filePath);
		if (!f.exists()) {
			return;
		}
		FileInputStream fs = new FileInputStream(f);
		int fileLength = fs.available();
		resp.setHeader("Content-Length", String.valueOf(fileLength));

		byte data[] = new byte[fileLength];
		fs.read(data); // 读数据
		fs.close();
		OutputStream toClient = resp.getOutputStream(); // 得到向客户端输出二进制数据的对象
		toClient.write(data); // 输出数据
		toClient.close();
	}

	@Override
	public void afterPropertiesSet() throws Exception {

	}
}
